package com.esd.device.controller;

import com.esd.common.pojo.R;
import com.esd.device.entity.vo.DeviceVo;
import com.esd.device.task.DeviceConstants;
import com.esd.device.utils.Modbus_Tcp_Utils;
import com.esd.device.utils.TcpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 尘埃粒子计数器 控制器
 */
@Slf4j
@RestController
@RequestMapping("dustTcp")
public class DustTCPController {

    @Autowired
    private Modbus_Tcp_Utils tcpUtils ;

    @PostMapping("searchDetail")
    public R searchDetail(@RequestBody DeviceVo deviceVo){
        String stationId = deviceVo.getStationId();
        int slaveId = Integer.parseInt(stationId);
        ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
        reentrantLock.lock();
        TcpResult tcpResult = null ;
        try {
            tcpResult = tcpUtils.readData(
                    deviceVo.getServerIp() ,
                    deviceVo.getServerPort(),
                    300,
                    slaveId,
                    0,
                    28) ;
        } catch (Exception e) {
            log.error("加锁失败！！ {}" , e.getMessage() );
        } finally {
            reentrantLock.unlock();
        }
        if (tcpResult !=null) {
            if (tcpResult.getResult().equals("error")) {
                return R.error("可能网关停机了，请检查");
            } else if (tcpResult.getResult().isEmpty()) {
                return R.error("无返回数据，终端" + deviceVo.getStationId() + "是否正常运行？");
            } else {
                int[] datas = tcpResult.getDatas();
                long data1 = datas[1]* 65536L + datas[0]; // 0.3um个数
                long data2 = datas[3]* 65536L + datas[2]; // 0.5um个数
                long data3 = datas[5]* 65536L + datas[4]; // 1.0um个数
                long data4 = datas[7]* 65536L + datas[6]; // 2.5um个数
                long data5 = datas[9]* 65536L + datas[8]; // 5.0um个数
                long data6 = datas[11]* 65536L + datas[10]; // 10.0um个数
                int level = datas[26] ; // 洁净等级
                Map<String , String> result = new HashMap<>() ;
                result.put("data1", data1 + " 个");
                result.put("data2", data2 + " 个");
                result.put("data3", data3 + " 个");
                result.put("data4", data4 + " 个");
                result.put("data5", data5 + " 个");
                result.put("data6", data6 + " 个");
                result.put("level", (level+1) + "");
                return R.ok(result);
            }
        }else {
            return R.error("数据查询失败!!");
        }
    }

    @PostMapping("getParameters")
    public R getParameters(@RequestBody DeviceVo deviceVo){
        String stationId = deviceVo.getStationId();
        int slaveId = Integer.parseInt(stationId);
        ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
        reentrantLock.lock();
        TcpResult tcpResult = null ;
        try {
            tcpResult = tcpUtils.readData(
                    deviceVo.getServerIp() ,
                    deviceVo.getServerPort(),
                    300,
                    slaveId,
                    125,
                    7) ;
        } catch (Exception e) {
            log.error("加锁失败！！ {}" , e.getMessage() );
        } finally {
            reentrantLock.unlock();
        }
        if (tcpResult !=null) {
            if (tcpResult.getResult().equals("error")) {
                return R.error("可能网关停机了，请检查");
            } else if (tcpResult.getResult().isEmpty()) {
                return R.error("无返回数据，终端" + deviceVo.getStationId() + "是否正常运行？");
            } else {
                int[] datas = tcpResult.getDatas();
                Map<String, Integer> result = new HashMap<>() ;
                int workMod = datas[0];
                int lxInterval = datas[1]; // 连续模式延时
                int jxInterval = datas[2]; // 间歇模式延时
                int jxTime = datas[3]; // 间歇模式持续时间
                int jxStopTime = datas[4]; // 间歇模式停止时间
                int onceInterval = datas[5]; // 单次模式延时时间
                int onceTime = datas[6]; // 单次模式持续时间
                result.put("workMod" , workMod) ;
                result.put("lxInterval" , lxInterval) ;
                result.put("jxInterval" , jxInterval) ;
                result.put("jxTime" , jxTime) ;
                result.put("jxStopTime" , jxStopTime) ;
                result.put("onceInterval" , onceInterval) ;
                result.put("onceTime" , onceTime) ;
                return R.ok(result);
            }
        }else {
            return R.error("数据查询失败!!");
        }
    }

    /**
     * @param registerNum 寄存器编号
     * @param num 寄存器写入数据
     */
    @PostMapping("setParameters/{registerNum}/{num}")
    public R setParameters(@RequestBody DeviceVo deviceVo , @PathVariable Integer registerNum , @PathVariable Integer num){
        String stationId = deviceVo.getStationId();
        int slaveId = Integer.parseInt(stationId);
        ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
        reentrantLock.lock();
        TcpResult tcpResult = null ;
        try {
            tcpResult = tcpUtils.writeData(
                    deviceVo.getServerIp() ,
                    deviceVo.getServerPort(),
                    300,
                    slaveId,
                    registerNum,
                    new int[]{num}) ;
        } catch (Exception e) {
            log.error("加锁失败！！ {}" , e.getMessage() );
        } finally {
            reentrantLock.unlock();
        }
        if (tcpResult !=null) {
            if (tcpResult.getResult().equals("error")) {
                return R.error("可能网关停机了，请检查");
            } else if (tcpResult.getResult().isEmpty()) {
                return R.error("无返回数据，终端" + deviceVo.getStationId() + "是否正常运行？");
            } else {
                return R.ok("参数设置成功！！") ;
            }
        }else {
            return R.error("请先关闭采样再设置!!");
        }
    }

    @PostMapping("/samplingOn/{status}")
    public R samplingOn(
            @RequestBody DeviceVo deviceVo ,
            @PathVariable Integer status
    ){
        String stationId = deviceVo.getStationId();
        int slaveId = Integer.parseInt(stationId);
        int[] datas = {status};
        ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
        reentrantLock.lock();
        TcpResult tcpResult = null ;
        try {
            tcpResult = tcpUtils.writeData(
                    deviceVo.getServerIp() ,
                    deviceVo.getServerPort(),
                    300,
                    slaveId,
                    50,
                    datas) ;
        } catch (Exception e) {
            log.error("加锁失败！！ {}" , e.getMessage() );
        } finally {
            reentrantLock.unlock();
        }
        String statusStr = status == 1 ? "开启":"停止" ;
        if (tcpResult !=null) {
            if (tcpResult.getResult().equals("error")) {
                return R.error("可能网关停机了，请检查");
            } else if (tcpResult.getResult().isEmpty()) {
                return R.error("无返回数据，终端" + deviceVo.getStationId() + "是否正常运行？");
            } else {
                return R.ok("采样" + statusStr + "成功！！");
            }
        }else {
            return R.error("采样" + statusStr + "失败!!");
        }
    }

}
